package com.winkyle.woodenfish.util;

import android.content.Context;
import android.util.Log;

import com.squareup.okhttp.Interceptor;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import java.io.IOException;

/**
 * @author winkyle
 * @date 2018/06/19
 * @description cookie拦截器(用于请求之前拦截)
 */

public class CookiesAddInterceptor implements Interceptor {
    private String TAG = "CookiesAddInterceptor";
    private Context context;

    public CookiesAddInterceptor(Context context) {
        this.context = context;
    }

    /**
     * @description 若Cookie不为空，则为请求头设置Cookie
     * @param chain
     * @return
     * @throws IOException
     */
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        Request request;
        if(UserConfig.getInstance(context).getCookie()==null){
            request = builder.build();
        } else {
            //打印当前Cookie
            Log.d(TAG,UserConfig.getInstance(context).getCookie());
            request = builder.addHeader("Cookie", UserConfig.getInstance(context).getCookie())
                    .build();
        }
        //打印网络请求的一些信息
        Log.d(TAG,request.toString());
        return chain.proceed(request);
    }
}
